package com.auth.domain.service.impl;

import com.auth.common.util.IPageUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.auth.control.model.RoleDto;
import com.auth.domain.mapper.authmanage.RoleMapper;
import com.auth.domain.module.po.authmanage.Role;
import com.auth.domain.module.po.authmanage.User;
import com.auth.domain.module.vo.authmanage.RoleVO;
import com.auth.domain.service.IRoleService;
import com.bean.ObjectMapperUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author cyj
 * @since 2020-10-20
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Override
    public Role getByName(String roleName) {
        Role condition = new Role().setRoleName(roleName);
        return this.baseMapper.selectOne(new QueryWrapper<Role>(condition));
    }

    @Override
    public RoleVO selectRole(Long id) {
        Role role = this.getById(id);
        return ObjectMapperUtils.clone(role, RoleVO.class);
    }

    @Override
    public RoleVO deleteRole(Long id) {
        RoleVO role = this.selectRole(id);
        this.removeById(id);
        return role;
    }

    @Override
    public RoleVO updateRole(RoleDto roleDto) {
        Role role = ObjectMapperUtils.clone(roleDto, Role.class);
        this.updateById(role);
        return ObjectMapperUtils.clone(role, RoleVO.class);
    }

    @Override
    public RoleVO saveRole(RoleDto roleDto) {
        Role role = ObjectMapperUtils.clone(roleDto, Role.class);
        this.save(role);
        return this.selectRole(roleDto.getId());
    }

    @Override
    public IPage<RoleVO> getRoles(Page page) {
        IPage<User> result = this.page(page);
        return IPageUtil.copy(result, RoleVO.class);
    }

    @Override
    public List<RoleVO> getByIds(Set<Long> roleIds) {
        if (CollectionUtils.isEmpty(roleIds)) {
            return Collections.EMPTY_LIST;
        }
        LambdaQueryWrapper<Role> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.in(Role::getId, roleIds);
        List<Role> list = this.list(lambdaQueryWrapper);
        return ObjectMapperUtils.clones(list, RoleVO.class);
    }

}
